package com.cheyun.netsalev3.viewmodel

import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.cheyun.netsalev3.bean.dm.DmHistory
import com.cheyun.netsalev3.repository.DmCallRecordRepository
import com.cheyun.netsalev3.widget.CallPopFragment

/**
 * @author Michael
 * @date  2018/12/19 - 17:54.
 */
class DmCallRecordActivityViewModel(var callRecordRepository: DmCallRecordRepository) : BaseViewModel() {
    var data = MutableLiveData<List<DmHistory>>()
    var listdata = ArrayList<DmHistory>()

    init {
        callRecordRepository.getData(this::setData)
    }

    var networkState = Transformations.switchMap(data) {
        callRecordRepository.networkState
    }

    private fun setData(item: List<DmHistory>) {
        listdata.addAll(item)
        data.postValue(listdata)
    }

    fun refresh() {
        callRecordRepository.getData(this::setData)
    }

    fun callPhone(view: View, item: DmHistory) {
        if (item.mp3_url.isNullOrBlank()) {
            Toast.makeText(view.context, "无法播放", Toast.LENGTH_LONG).show()
            return
        }

        var context = view.context
        if (context is AppCompatActivity) {
            var pop = CallPopFragment.newInstance(item.mp3_url, "00:00", secondToMin(item.mp3_len))
            pop.show(context.supportFragmentManager, "")
        }
    }

    fun secondToMin(v:Int):String{
        var min = v/60
        var s = v%60;
        if(min == 0)return s.toString() +" 秒     ";
        else{
            if(s == 0) return min.toString()+" 分     ";
            return min.toString()+" 分"+s.toString()+" 秒     "
        }
    }
}